

<template>
	<view class="container">
		
		<view class="logo"></view>
		
		<view class="title">微信登录</view>
		
		<button class="wx-login-btn" open-type="getUserInfo" @getuserinfo="wxLogin">微信登录</button>
	</view>
</template>

<script>
	export default {
		methods: {
			wxLogin(res) {
				
				if (res.mp.detail.userInfo) {
					// 用户已授权
					// console.log('userInfo',res.mp.detail.userInfo);
					uni.login({
						success: res => {
							// 获取登录凭证（code）
							const code = res.code
							console.log('code',code);
							
							// 向后台发送请求，获取用户的openid和session_key
							uni.request({
								url: '',//示例
								method: 'POST',
								data: {
									code: code,
									userInfo: res.mp.detail.userInfo
								},
								success: res => {
									// 登录成功，保存token
									uni.setStorageSync('token', res.data.token)
									// 跳转到首页
									uni.switchTab({
										url: '/pages/index/index'
									})
								},
								fail: err => {
									uni.showToast({
										title: '登录失败，请稍后再试',
										icon: 'none'
									})
								}
							})
						},
						fail: err => {
							uni.showToast({
								title: '登录失败，请稍后再试',
								icon: 'none'
							})
						}
					})
				} else {
					// 用户未授权
					uni.showToast({
						title: '请先授权登录',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-color: #fff;
	}

	.logo {
		width: 120rpx;
		height: 120rpx;
		background-image: url('/static/logo.png');
		background-size: cover;
	}

	.title {
		font-size: 28rpx;
		margin-top: 20rpx;
		color: #333;
	}

	.wx-login-btn {
		margin-top: 40rpx;
		width: 500rpx;
		height: 80rpx;
		background-color: #1aad19;
		border-radius: 40rpx;
		color: #fff;
		font-size: 32rpx;
	}
</style>